<template>
    <!-- el-card卡片组件  shadow 阴影的设置   body-style:设置内容样式  -->
    <el-card shadow="hover" :body-style="{padding:'20px'}">
        <!-- type 有6个值 6种颜色  size 按钮的大小 大 默认 下   -->
        <el-button type="primary" size="default" :icon="Plus" @click="addHandler" v-visite="'btn.Trademark.add'">添加</el-button>
        <!-- 表格:展示品牌的数据
            el-table 表格组件容器
            el-table-column:子组件
            自身都有自己的属性和方法
            v-loading 是获取数据的时候显示的圈圈
            element-loading-text 是圈圈下边展示的字
        -->
        <!-- border 是纵向边框默认是false data:是要展示的数据  -->
        <el-table border style="margin:10px 0" :data="tmObj.records" v-loading="loading" element-loading-text='努力加载中'>
            <!-- label 是列的头部  prop 展示的数据  type:可以设置列的形态  例如:复选,下标,箭头 -->
            <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
            <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
            <el-table-column label="品牌LOGO">
                <template v-slot="{row,$index}">
                    <!--v-slot 可以简化成#   row是底层给写好的回传数据 代表着数组中的每条数据 -->>
                    <!-- 这一列展示的不是文字而是其他东西,例如 图 组件 就要用插槽 -->
                    <img :src="row.logoUrl" alt="" style="width:100px;height:60px">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{row,$index}">
                    <el-button type="warning" size="small" :icon="Edit" @click="tmUpdate(row)"></el-button>




                    <el-popconfirm :title="`确定要删除${row.tmName}吗?`" @confirm="deleteT(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete" @click=""></el-button>
                        </template>
                    </el-popconfirm>




                </template>




            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <!-- 
            current-page 当前是第几页
            page-size   当前页展示几条数据
            page-sizes  下拉选择当前展示条数
            total        总数据
            pager-count  连续页码数 可以设置分页器能看见的按钮总个数
            background  是否为分页器添加背景颜色 false 或  true
            layout 组件布局 组件用,隔开 element 把分页器拆成了很多组件,用layout进行布局排列位置
            @current-change 当前页变化触发的回调
            @size-change 下拉修改每页条数时触发的回调
         -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" :pager-count="7"
            @current-change="getTradeMarkList" @size-change="sizeHandler" background>

        </el-pagination>

        <!-- 添加的弹出的组件 -->
        <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'" draggable>
            <el-form style="width: 80%" label-width="90px" :model="tmParams" :rules="rules" ref="formRef">
                <!--收集品牌名称地方-->
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input autocomplete="off" v-model='tmParams.tmName' />
                </el-form-item>
                <!--收集品牌lOGO地方
                action:上传图片上传的地址
                :show-file-list:控制是否显示上传成功后的文件名字
              -->
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>



            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确定</el-button>
                </span>
            </template>


        </el-dialog>

    </el-card>
</template>

<script setup lang="ts">
//引入element-plus提供的icon图标组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqTradeMarkList, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from '@/api/product/trademark/trademark'
import type { trademarkResponseData, tradmark } from "@/api/product/trademark/model/trademark";
//引入上传图片成功人家需要的类型
import type { UploadProps, FormInstance, FormRules } from "element-plus";
//保存分页器当前页码
let currentPage = ref<number>(1)
//保存当前页面显示几条数据
let pageSize = ref<number>(3)
//控制loading 响应式数据
let loading = ref<boolean>(false)
//控制dialog对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//from的REF 
let formRef = ref<FormInstance>()
//收集新增品牌数据-将来发请求给服务器
let tmParams = reactive<tradmark>({
    tmName: '',
    logoUrl: ''
})

let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: []
})

//点击删除的逻辑
const deleteT = async (id: number) => {
    await reqDeleteTradeMark(id)
    getTradeMarkList(currentPage.value)
}

//页面挂载时候发送请求
onMounted(() => {
    getTradeMarkList()
})
//点击取消的逻辑
const cancel = () => {
    dialogFormVisible.value = false
}
//点击添加按钮 清空表单数据
const addHandler = () => {
    dialogFormVisible.value = true
    tmParams.tmName = ''
    tmParams.id = ''
    tmParams.logoUrl = ''
    nextTick(() => {
        formRef.value?.resetFields()
    })
}


//发送请求获取页面数据
const getTradeMarkList = async (page: number = 1) => {
    loading.value = true
    currentPage.value = page
    let result = await reqTradeMarkList(currentPage.value, pageSize.value)
    loading.value = false
    tmObj.total = result.total
    tmObj.records = result.records

}
//点击分页器数字按钮时候触发   这个函数和上边函数功能一样,所以省略这个直接用上边函数代替
// const currentHandler = (page:number)=>{
//     currentPage.value = page
//     getTradeMarkList()
// }
//点击分页器下拉修改每天条数的回调   这个回调和上边回调不可以同事用作获取页面函数一起作为回调,因为你传的参数,他们两个无法区分
const sizeHandler = (limit: number) => {
    pageSize.value = limit
    getTradeMarkList()
}


//上传图片成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //response:上传图片成功服务器返回数据
    //图片学校远程服务器地址
    tmParams.logoUrl = response.data;
};

//图片上传成功之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    //图片相关的信息
    //外层约束类型
    if (
        rawFile.type == "image/jpeg" ||
        rawFile.type == "image/png" ||
        rawFile.type == "image/gif"
    ) {
        //约束大小1024B->1K->1M->1G->1T
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        return false;
    }
};
//点击确定按钮发送请求
const addOrUpdate = () => {

    formRef.value?.validate(async (flag) => {
        if (flag) {
            await reqAddOrUpdateTradeMark(tmParams);
            //对话框关闭
            dialogFormVisible.value = false;
            //再次获取最新的全部品牌的数据
            getTradeMarkList(tmParams.id ? currentPage.value : 1);
            ElMessage({
                message: tmParams.id ? "修改品牌成功" : '添加品牌成功',
                type: "success",
                duration: 800
            });
        } else {
            ElMessage({
                message: tmParams.id ? "修改品牌失败" : '添加品牌失败',
                type: "error",
                duration: 800
            });
        }
    })


};

//点击修改的逻辑
const tmUpdate = (row: tradmark) => {
    dialogFormVisible.value = true
    nextTick(() => {
        formRef.value?.resetFields()
        tmParams.id = row.id
        tmParams.tmName = row.tmName
        tmParams.logoUrl = row.logoUrl
    })


}

//表单验证的逻辑
const rules = reactive<FormRules>({
    tmName: [{
        required: true, message: '你家品牌名称是空的么?', trigger: 'blur'
    }],
    logoUrl: [{
        required: true, message: '你家品牌LOGO是空的么?'
    }]
})

</script>

<style scoped>
/**上传照片的样式**/
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>